package com.wp.file.controller;

import com.wp.file.common.BaseContext;
import com.wp.file.common.R;
import com.wp.file.pojo.Note;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/notes")
public class NoteController {
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/upload")
    public R<String> upload (@RequestBody Note note){
        Long userid = BaseContext.getCurrentId();
        Object valueF = redisTemplate.opsForHash().get(userid.toString(), note.getTitle());
        if(valueF != null){
            return R.error("已存在该标题!");
        }
        note.setUpdateTime(LocalDateTime.now());
        redisTemplate.opsForHash().put(userid.toString(),note.getTitle(),note);
        Map<Object,Object> map = redisTemplate.opsForHash().entries(userid.toString());
        log.info(map.toString());
        return R.success("笔记上传成功!");
    }

    //查询全部
    @GetMapping("/select")
    public R<List<Note>> select(){
        Long userid = BaseContext.getCurrentId();
        //获取所有hash中所有值
        List<Note> values = (List<Note>) redisTemplate.opsForHash().values(userid.toString());
        values.sort(Comparator.comparing(Note::getUpdateTime).reversed());
        System.out.println(values.toString());
//        List<String> titleList = values.stream().map(value -> {
//            String title = value.getTitle();
//            return title;
//        }).collect(Collectors.toList());
        return R.success(values);
    }

//    @GetMapping("/see")
//    public  R<String> seeNote(@PathParam("title") String title){
//        Long currentId = BaseContext.getCurrentId();
//        Object text = redisTemplate.opsForHash().get(currentId.toString(),title);
//        String textOver = (String) text;
//        return R.success(textOver);
//    }


}
